import 'dart:async';
import 'package:flutter/material.dart';
import "./Image.dart";

class Swiper extends StatefulWidget {
  List list;
  double height;
  Swiper({super.key, required this.list, this.height = 200});

  @override
  State<Swiper> createState() => _SwiperState();
}


class _SwiperState extends State<Swiper> {
  late List _list;
  int _currentIndex = 0;
  late Timer _timer;
  late PageController _pageController;
  @override
  void initState() {
    _list = widget.list.map((item) => ImageWget(item)).toList();

    super.initState();
    _timer = Timer.periodic(
      const Duration(seconds: 3),
      (t) {
        setState(() {
          _currentIndex = (_currentIndex + 1) % _list.length;
          // 跳转到下一页
          _pageController.animateToPage(
            _currentIndex,
            duration: Duration(milliseconds: 200),
            curve: Curves.linear,
          );
        });
      },
    );

    // 页面控制器
    _pageController = PageController(
      initialPage: _currentIndex,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
    _pageController.dispose();
  }

  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: 200,
          child: PageView.builder(
            controller: _pageController,
            itemCount: 1000,
            itemBuilder: (context, index) {
              return _list[index % _list.length];
            },
            onPageChanged: (index) {
              setState(() {
                _currentIndex = (index % _list.length);
              });
            },
          ),
        ),
        Positioned(
          bottom: 10,
          left: 0,
          right: 0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(
              _list.length,
              (index) => Container(
                width: 10,
                height: 10,
                margin: const EdgeInsets.all(5),
                decoration: BoxDecoration(
                  color: _currentIndex == index ? Colors.red : Colors.teal,
                  // borderRadius: BorderRadius.circular(5),
                  shape: BoxShape.circle,
                ),
              ),
            ).toList(),
          ),
        )
      ],
    );
  }
}
